import cv2
import numpy as np

# 1. 图片输入
image_np = cv2.imread('txsb.jpg')


# 2. HSV空间转换
hsv_image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)

# 3. 制作掩膜
blue_low = np.array([110, 80, 80])
blue_high = np.array([120, 255, 255])
mask1 = cv2.inRange(hsv_image_np, blue_low, blue_high)

orange_low = np.array([11, 43, 46])
orange_high = np.array([25, 255, 255])
mask2 = cv2.inRange(hsv_image_np, orange_low, orange_high)

# 形态学降噪：先腐蚀（消除小噪声），再膨胀（恢复主体形状）
kernel = np.ones((3, 3), np.uint8)
mask1 = cv2.erode(mask1, kernel, iterations=1)
mask1 = cv2.dilate(mask1, kernel, iterations=1)

mask2 = cv2.erode(mask2, kernel, iterations=1)
mask2 = cv2.dilate(mask2, kernel, iterations=1)

# 合二为一：位或
mask_image_np = cv2.bitwise_or(mask1, mask2)

# 4. 与运算
color_image_np = cv2.bitwise_and(image_np, image_np, mask=mask_image_np)

# 5. 图像输出
cv2.imshow('mask1', mask1)
cv2.imshow('mask2', mask2)
cv2.imshow('mask_image_np', mask_image_np)
cv2.imshow('color_image_np', color_image_np)
cv2.imwrite('color_image_np.png', color_image_np)
cv2.waitKey(0)
